//职员管理

import React, {Component} from 'react';
import app from '../app';
import {
    Form,
    Input,
    Button,
    Table,
    Modal,
    Row,
    Upload,
    Col,
    DatePicker,
    Select,
    Radio,
    InputNumber,
    TreeSelect
} from 'antd';
import {project, collage, type, invitation} from '../value';
import '../css/other.css';
import '../css/teamBuying.css';
import moment from 'moment';
import {config} from "../config";
import {GoodLists} from '../components/operateManage';


const FormItem = Form.Item;
const confirm = Modal.confirm;
const RangePicker = DatePicker.RangePicker;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Option = Select.Option;
const SHOW_PARENT = TreeSelect.SHOW_PARENT;

const loopType = (type, data) => {
    let typeList = [];
    data.map((item, index) => {
        if (type.type_id === item.type_parentId) {
            item.label = item.type_name;
            item.value = item.type_id;
            item.key = item.type_id;
            typeList.push(item);
            type.children = typeList;
            loopType(item, data);
        } else {

        }
    })
};

class TeamBuying extends Component {
    constructor(props) {
        super(props);
        this.state = {
            pagination: {current: 0, pageSize: 0, total: 0},
            value: '1',
            activityName: '',
            start_time: '',
            end_time: '',
            activityTime: 0,
            activityNum: 0,
            activityDetail: '',
            activityAccount: 0,
            positionId: [],
            teamPrice: '',
            paramName: '',
            paramType: '',
            paramPrice: 0,
            shopType: [],
            data: [],
            dataList: [],
            typeSearch: [],
            operateTypeText: ''
        }
    }

    columns = [
        {
            title: '序号',
            dataIndex: 'order_number'
        },
        {
            title: '商品编号',
            dataIndex: 'goods_code'
        },
        {
            title: '主图',
            dataIndex: 'file_path',
            render: file_path => {
                return (
                    <img src={config.imgServerUrl + file_path} style={{width: '70px', height: '70px'}}/>
                )
            }
        },
        {
            title: '商品名',
            dataIndex: 'goods_name'
        },
        {
            title: '分类',
            dataIndex: 'typeName'
        },
        {
            title: '商品售价',
            dataIndex: 'goods_price'
        },
        {
            title: '团购价',
            dataIndex: this.columns,
            render: data => {
                return (
                    <span>
                        {
                            data.goods_isSpecPrice == '1' ? '' : <Input placeholder={'团购价'}
                                                                        style={{width: '100px'}}
                                                                        type={'number'}
                                                                        value={data.teamPrice}
                                                                        onChange={(e) => this.handleTeamPriceOnChange1(e, data.order_number)}
                            />
                        }
                    </span>
                )
            }
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (<div>
                    <Button type='danger' onClick={() => this.handleCancel(data)}>取消团购</Button>
                </div>)
            }
        },
    ];


    render() {
        const {start_time, end_time, activityName, activityTime, activityNum, peopleNum, activityDetail, activityAccount, teamPrice, paramName, paramPrice} = this.state;
        const rowSelection = {
            // 表格中复选框发生变化时
            onChange: (selectedRowKeys, selectedRows) => {
                let positionId = [];
                let positionName = [];
                positionId = selectedRowKeys;
                selectedRows.forEach((item) => {
                    positionName.push(item.role_name);
                });
                console.log(selectedRowKeys);
                this.setState({
                    positionId: positionId,  //批量选中的职位ID
                    positionName: positionName,
                    selectCount: selectedRowKeys.length, //一共选择的职位数量
                })
            },
            selectedRowKeys: this.state.positionId

        };
        const expandedRowRender = (e) => {
            console.log('000000000');
            console.log(e);
            if (!e.skuList) {
                e.skuList = [];
            }
            return (
                <Row>
                    {
                        e.skuList.map((item, index) => {
                            let text = '';
                            if (item.type === 1) {
                                text = '香辣味';
                            } else {
                                text = '其它';
                            }
                            return (
                                <Col span={12} style={{marginTop: 10}} key={index}>
                                    <div className={'baseInfoItem'}>
                                        <div style={{
                                            width: 120,
                                            paddingTop: 5
                                        }}>{item.goods_sku_record.replace(/,/g, "  ")}</div>
                                        <div style={{width: 100, paddingTop: 5}}>售价：{item.goods_sku_price}</div>
                                        <div style={{width: 70, paddingTop: 5}}><span style={{color: 'red'}}>*</span>团购价：
                                        </div>
                                        <Input style={{width: 70}} type={'number'} value={item.teamPrice}
                                               onChange={(event) => this.handleTeamPriceOnChange(event, e.order_number, index)}/>
                                    </div>
                                </Col>
                            )
                        })
                    }
                </Row>
            )
        };
        return (
            <div style={{paddingBottom: 25}}>
                <div className="pageTitle">
                    新增团购活动
                </div>
                <Row className={'baseInfoContainer'}>
                    <Row className={'baseInfoHeader'}>基本信息</Row>
                    <Row className={'baseInfoBody'}>
                        <div className={'baseInfoItem'}>
                            <div style={{width: 70, paddingTop: 5}}>活动名</div>
                            <Input placeholder={'活动名'} value={activityName} style={{width: 200}}
                                   onChange={(e) => this.handleActivityName(e)}/>
                            <div style={{width: 60, paddingTop: 5, marginLeft: 40}}>有效期</div>
                            <RangePicker
                                onChange={(e) => this.handleTimeChange(e)}/>
                        </div>
                        <div className={'baseInfoItem'} style={{marginTop: 20}}>
                            <div style={{width: 70, paddingTop: 5}}>拼单时长</div>
                            <RadioGroup onChange={this.onChange} value={this.state.value} style={{padding: 5}}>
                                <Radio value={'1'}>当天</Radio>
                                <Radio value={'2'}>时长</Radio>
                            </RadioGroup>
                            <Input style={{width: 60}} value={activityTime}
                                   onChange={(e) => this.handleActivityTime(e)} type={'number'}/>
                            <div style={{width: 60, paddingTop: 5, marginLeft: 10}}>小时</div>
                        </div>
                        <div className={'baseInfoItem'} style={{marginTop: 20}}>
                            <div style={{width: 70, paddingTop: 5}}>参与次数</div>
                            <Input style={{width: 60}} type={'number'} value={activityNum}
                                   onChange={(e) => this.handleActivityNum(e)}/>
                            <div style={{width: 60, paddingTop: 5, marginLeft: 10}}>天/次</div>
                        </div>
                        <div className={'baseInfoItem'} style={{marginTop: 20}}>
                            <div style={{width: 70, paddingTop: 5}}>活动说明</div>
                            <TextArea style={{width: 200}} value={activityDetail}
                                      onChange={(e) => this.handleActivityDetail(e)}></TextArea>
                        </div>
                    </Row>
                </Row>
                <Row className={'baseInfoContainer'}>
                    <Row className={'baseInfoBody'} style={{padding: '30px 20px'}}>
                        <div className={'baseInfoItem'}>
                            <div style={{width: 70, paddingTop: 5}}>拼单人数</div>
                            <Input style={{width: 100}} type={'number'} value={peopleNum}
                                   onChange={(e) => this.handleActivityPeopleNum(e)}/>
                            <div style={{width: 70, paddingTop: 5, marginLeft: 40}}>可购买数量</div>
                            <Input style={{width: 100}} type={'number'} value={activityAccount}
                                   onChange={(e) => this.handleActivityAccount(e)}/>
                            <div style={{width: 70, paddingTop: 5, marginLeft: 40}}>团购金额>=</div>
                            <Input style={{width: 70}} type={'number'} value={teamPrice}
                                   onChange={(e) => this.handleTeamPrice(e)}/>
                            <div style={{width: 60, paddingTop: 5, marginLeft: 10}}>元</div>
                        </div>
                    </Row>
                </Row>

                <Row className={'baseInfoContainer'}>
                    <Row className={'baseInfoBody'}>
                        <div className={'baseInfoItem'}>
                            <GoodLists chooseData={this.state.dataList}
                                       handleChooseGoods={(data) => this.handleChooseGoods(data)}>新增商品</GoodLists>
                        </div>
                        <div className={'baseInfoItem'} style={{marginTop: 30}}>
                            <Input style={{width: 200}} placeholder={'商品名/编号'} value={paramName}
                                   onChange={(e) => this.handleParamName(e)}
                                   onPressEnter={(e) => this.handleSearchByName(e)}/>
                            <div className={"typeStyle"}>分类</div>
                            <TreeSelect
                                treeData={this.state.shopType}
                                treeCheckable={true}
                                multiple={true}
                                onSelect={this.getShopType}
                                showCheckedStrategy={SHOW_PARENT}
                                searchPlaceholder='请选择'
                                style={{width: 200}}
                            />
                            <div style={{width: 60, marginLeft: 20}}>
                                <Button type={'primary'} onClick={() => this.handleSearchBtn()}>搜索</Button>
                            </div>
                        </div>
                        <div className={'baseInfoItem'} style={{marginTop: 20}}>
                            <div className={"teamPriceStyle"}>团购价</div>
                            <Input style={{width: 70}} type={'number'} value={paramPrice}
                                   onChange={(e) => this.handleParamPrice(e)}/>
                            <div style={{width: 100, marginLeft: 20}}>
                                <Button type={'primary'} onClick={() => this.handleSetting()}>批量设置</Button>
                            </div>
                        </div>

                        <Row style={{marginTop: 20}}>
                            <Table
                                rowSelection={rowSelection}
                                columns={this.columns}
                                rowKey={record => record.goods_id}
                                dataSource={this.state.data}
                                loading={this.state.loading}
                                expandedRowRender={expandedRowRender}
                                pagination={this.state.pagination}
                                onChange={this.handleTableChange}
                            />
                        </Row>
                        <Row style={{textAlign: 'center', marginTop: 20}}>
                            <Button type={'primary'} onClick={() => this.handleSubmit()}>提交并发布</Button>
                        </Row>
                    </Row>
                </Row>
            </div>
        )
    }

    /**
     * 初始化
     */
    componentDidMount() {
        //this.searchProject({});
        this.requestShopType();
    }

    /**
     * 处理活动名变化事件
     * @param e
     */
    handleActivityName(e) {
        this.setState({activityName: e.target.value});
    }

    /**
     * 处理有效期变化事件
     * @param e
     */
    handleTimeChange(e) {
        if (e && e.length === 2) {
            const start_time = moment(e[0]._d).format('YYYY-MM-DD');
            const end_time = moment(e[1]._d).format('YYYY-MM-DD');
            this.setState({start_time, end_time});
        } else {
            this.setState({start_time: '', end_time: ''});
        }
    }

    /**
     * 处理活动时间变化事件
     * @param e
     */
    handleActivityTime(e) {
        this.setState({activityTime: e.target.value});
    }

    /**
     * 处理活动参与次数变化
     * @param e
     */
    handleActivityNum(e) {
        this.setState({activityNum: e.target.value});
    }

    /**
     * 处理活动说明变化
     * @param e
     */
    handleActivityDetail(e) {
        this.setState({activityDetail: e.target.value});
    }

    /**
     * 购买数量变化
     * @param e
     */
    handleActivityAccount(e) {
        this.setState({activityAccount: e.target.value});
    }

    /**
     * 拼单人数
     * @param e
     */
    handleActivityPeopleNum(e) {
        this.setState({peopleNum: e.target.value});
    }

    /**
     * 团购金额变化
     * @param e
     */
    handleTeamPrice(e) {
        this.setState({teamPrice: e.target.value});
    }

    /**
     * 搜索条件变化
     * @param e
     */
    handleParamName(e) {
        this.setState({paramName: e.target.value});
    }

    /**
     * 搜索条件变化
     * @param e
     */
    handleParamType(e) {
        this.setState({paramType: e});
    }

    /**
     * 批量设置金额
     * @param e
     */
    handleParamPrice(e) {
        this.setState({paramPrice: e.target.value});
    }

    /**
     * 批量设置
     */
    handleSetting() {
        let {paramPrice, positionId, data, dataList} = this.state;
        if (positionId.length <= 0) {
            app.alert('请选择要设置的商品', 'info', 1);
            return;
        }
        if (!paramPrice || isNaN(paramPrice) || paramPrice < 0) {
            app.alert('请设置正确的团购价', 'info', 1);
            return;
        }

        for (let i = 0; i < positionId.length; i++) {
            let goods_id = positionId[i];
            for (let j = 0; j < data.length; j++) {
                if (data[j].goods_id === goods_id) {
                    let item = data[j];
                    if (item.goods_isSpecPrice === '1') {
                        for (let k = 0; k < item.skuList.length; k++) {
                            item.skuList[k].teamPrice = paramPrice;
                        }
                    } else {
                        item.teamPrice = paramPrice;
                    }
                    break;
                }
            }
            for (let j = 0; j < dataList.length; j++) {
                if (dataList[j].goods_id === goods_id) {
                    let item = dataList[j];
                    if (item.goods_isSpecPrice === '1') {
                        for (let k = 0; k < item.skuList.length; k++) {
                            item.skuList[k].teamPrice = paramPrice;
                        }
                    } else {
                        item.teamPrice = paramPrice;
                    }
                    break;
                }
            }
        }
        this.setState({data, dataList});
    }

    /**
     * 处理页码、显示数量变化事件
     * @param pagination
     * @param filters
     * @param sorter
     */
    handleTableChange = (pagination, filters, sorter) => {
        const current = pagination.current;
        const size = pagination.pageSize;
        const pagination1 = this.state.pagination;
        pagination1.current = current;
        pagination1.pageSize = size;
        this.setState({pagination: pagination1});
    };

    /**
     * 查找项目列表
     * @param param
     */
    searchProject(param) {
        let _this = this;
        _this.setState({loading: true});
        app.post(project.SEARCH_PROJECT, param).then(result => {
            if (result.code === 1) {
                const data = result.data;
                for (let i = 0; i < data.length; i++) {
                    const content = data[i].project_content;
                    if (content.length > 10) {
                        data[i].project_content = content.substr(0, 10) + '...';
                    }
                }
                const pagination = {total: data.length, current: 1, pageSize: 10};
                this.setState({pagination, data: data, loading: false});
            } else {
                app.alert(result.msg, 'success', 2);
                const pagination = {total: 0, current: 0, pageSize: 0};
                this.setState({pagination, data: [], loading: false});
            }
        });
    }

    /**
     * 处理类型变化
     * @param e
     */
    handleTypeOnChange(e) {
        this.setState({currentType: e.target.value});
    }

    onChange = (e) => {
        this.setState({value: e.target.value});
    };

    /**
     * 取消团购
     * @param data
     */
    handleCancel(dataTemp) {
        const _this = this;
        confirm({
            content: '您确定要取消该团购吗？',
            onOk() {
                let {data, dataList} = _this.state;
                let {order_number, goods_id} = dataTemp;
                data.splice(order_number - 1, 1);
                for (let i = 0; i < dataList.length; i++) {
                    if (dataList[i].goods_id === goods_id) {
                        dataList.splice(i, 1);
                        break;
                    }
                }
                _this.setState({data, dataList});
            },
            onCancel() {
            },
        });
    }

    /**
     * 提交并发布
     */
    handleSubmit() {
        const {
            activityName,
            activityTime,
            activityNum,
            peopleNum,
            activityDetail,
            activityAccount,
            teamPrice,
            value,
            start_time,
            end_time,
            dataList
        } = this.state;
        if (!activityName) {
            app.alert('活动名不能为空！', 'info', 1);
            return;
        }
        if (!start_time || !end_time) {
            app.alert('请选择活动有效期！', 'info', 1);
            return;
        }
        if (value === '2') {
            if (!activityTime || isNaN(activityTime) || activityTime <= 0) {
                app.alert('请拼单时长！', 'info', 1);
                return;
            }
        }

        if (!activityNum || isNaN(activityNum) || activityNum <= 0) {
            app.alert('请设置参与次数！', 'info', 1);
            return;
        }
        if (!peopleNum || isNaN(peopleNum) || peopleNum <= 0) {
            app.alert('请设置拼单人数！', 'info', 1);
            return;
        }
        if (!activityAccount || isNaN(activityAccount) || activityAccount <= 0) {
            app.alert('请设置可购买数量！', 'info', 1);
            return;
        }
        if (!teamPrice || isNaN(teamPrice) || teamPrice <= 0) {
            app.alert('请设置团购金额！', 'info', 1);
            return;
        }
        if (dataList.length <= 0) {
            app.alert('请选择团购商品！', 'info', 1);
            return;
        }

        let goodsList = [];
        let hasPrice = true;
        for (let i = 0; i < dataList.length; i++) {
            let item = dataList[i];
            let tempItem = {};
            if (item.goods_isSpecPrice === '1') {
                for (let j = 0; j < item.skuList.length; j++) {
                    let item2 = item.skuList[j];
                    if (!item2.teamPrice || isNaN(item2.teamPrice) || item2.teamPrice <= 0) {
                        hasPrice = false;
                        break;
                    }
                    tempItem.goods_sku_id = item2.goods_sku_id;
                    tempItem.goods_id = item.goods_id;
                    tempItem.collage_goods_price = item2.teamPrice;
                    tempItem.collage_goods_isSpecPrice = '1';
                    tempItem.collage_goods_goodsPrice = item2.goods_sku_price;
                    tempItem.collage_goods_skuRecord = item2.goods_sku_record;
                    goodsList.push(tempItem);
                }
            } else if (item.goods_isSpecPrice === '2') {
                if (!item.teamPrice || isNaN(item.teamPrice) || item.teamPrice <= 0) {
                    hasPrice = false;
                    break;
                }
                tempItem.goods_id = item.goods_id;
                tempItem.collage_goods_price = item.teamPrice;
                tempItem.collage_goods_isSpecPrice = '2';
                tempItem.collage_goods_goodsPrice = item.goods_price;
                goodsList.push(tempItem);
            }
            if (!hasPrice) {
                break;
            }
        }

        if (!hasPrice) {
            app.alert('请设置团购价', 'info', 1);
            return;
        }

        const param = {
            collage_name: activityName,
            collage_startTime: start_time,
            collage_endTime: end_time,
            collage_style: value,
            collage_time: activityTime,
            collage_frequency: activityNum,
            collage_explain: activityDetail,
            collage_number: peopleNum,
            collage_account: activityAccount,
            collage_overPrice: teamPrice,
            goodsList,
        };
        console.log(goodsList);
        app.post(collage.ADD_COLLAGE, param).then((res) => {
            if (res.code === 1) {
                app.alert('添加成功', 'success', 1);
            } else {
                app.alert(res.msg, 'info', 1);
            }
        })
    }


    /**
     * 选择商品
     * @param data
     */
    handleChooseGoods(data) {
        let goodData = this.state.data;
        const _this = this;
        for (let i = 0; i < data.length; i++) {
            let goods_id = data[i].goods_id;
            app.post(collage.SEARCH_COLLAGE_GOODS_BY_ADD, {goods_id}).then((res) => {
                if (res.code === 1) {
                    goodData.push(res.data);
                    _this.setState({dataList: goodData});
                    let {paramName, typeSearch} = _this.state;
                    let param = {
                        paramName,
                        typeSearch
                    };
                    _this.searchGoodsList(param);
                } else {
                    app.alert(res.msg, 'info', 1);
                }
            });
        }
    }

    /**
     * 处理有规格时团购价的修改
     * @param e
     * @param id
     * @param index
     */
    handleTeamPriceOnChange(e, order_number, index) {
        let value = e.target.value;
        let {data} = this.state;
        let item = data[order_number - 1];
        item.skuList[index].teamPrice = value;
        this.setState(data);
    }

    /**
     * 处理有规格时团购价的修改
     * @param e
     * @param index
     */
    handleTeamPriceOnChange1(e, index) {
        let value = e.target.value;
        let {data} = this.state;
        let item = data[index - 1];
        item.teamPrice = value;
        this.setState(data);
    }


    /**
     * 处理搜索框回车事件
     * @param e
     */
    handleSearchByName(e) {
        let {paramName, typeSearch} = this.state;
        let param = {
            paramName,
            typeSearch
        };
        this.searchGoodsList(param);
    }

    /**
     * 处理搜索按钮事件
     */
    handleSearchBtn() {
        let {paramName, typeSearch} = this.state;
        let param = {
            paramName,
            typeSearch
        };
        this.searchGoodsList(param);
    }

    /**
     * 获取分类
     */
    requestShopType() {
        let msg = {};
        let temp;
        app.post(type.SEARCH_ALL_TYPE, {}).then(req => {
            if (req.code == 1) {
                let firstMenu = [];
                req.data.map((item) => {
                    // 先查到最顶层数据
                    temp = {
                        label: item.type_name,
                        value: item.type_id,
                        type_id: item.type_id,
                        type_isable: item.type_isable,
                        type_level: item.type_level,
                        type_name: item.type_name,
                        type_parentId: item.type_parentId,
                        key: item.type_id
                    };
                    if (!item.type_parentId) {
                        firstMenu.push(temp);
                    }
                });
                firstMenu.map((item) => {
                    loopType(item, req.data);  //根据最顶层的数据所含的子数据的ID和所有的分类ID比较，相同的则为他的子数据
                });
                this.setState({shopType: firstMenu});
            } else if (req.msg == '查询无记录') {
                app.alert('请先添加分类', 'error', 3);
            } else if (req.code == 2) {
                app.alert(req.msg, 'error', 3)
            }
        });
    }


    // 获取商家选中的分类
    getShopType = (value, label, extra) => {
        console.log(value, label, extra);
        let selectShopType = [];
        let temp = {};
        extra.checkedNodes.forEach((item) => {
            temp = {
                type_id: item.props.type_id,
                type_level: item.props.type_level,
                type_name: item.props.type_name,
                type_parentId: item.props.type_parentId
            };
            selectShopType.push(temp);
        });
        const {paramName} = this.state;
        console.log(selectShopType);
        this.setState({typeSearch: selectShopType});
        let param = {
            typeSearch: selectShopType,
            paramName
        };
        this.searchGoodsList(param);
    };

    /**
     * 查找商品
     */
    searchGoodsList(param) {
        let {dataList} = this.state;
        let {paramName, typeSearch} = param;
        let tempData = [];
        for (let i = 0; i < dataList.length; i++) {
            if (paramName && typeSearch.length <= 0) {
                const re = new RegExp(paramName);
                if (re.test(dataList[i].goods_name) || re.test(dataList[i].goods_code)) {
                    tempData.push(dataList[i]);
                }
            } else if (!paramName && typeSearch.length > 0) {
                for (let j = 0; j < typeSearch.length; j++) {
                    if (typeSearch[j].type_name === dataList[i].typeName) {
                        tempData.push(dataList[i]);
                        break;
                    }
                }
            } else if (paramName && typeSearch.length > 0) {
                const re = new RegExp(paramName);
                if (re.test(dataList[i].goods_name) || re.test(dataList[i].goods_code)) {
                    for (let j = 0; j < typeSearch.length; j++) {
                        if (typeSearch[j].type_name === dataList[i].typeName) {
                            tempData.push(dataList[i]);
                            break;
                        }
                    }
                }
            } else {
                tempData = dataList;
            }
        }
        for (let i = 0; i < tempData.length; i++) {
            tempData[i].order_number = i + 1;
        }
        const pagination = {
            current: 1,
            pageSize: 10,
            total: tempData.length
        };
        this.setState({data: tempData, positionId: [], pagination});
    }

}

const TeamBuyings = Form.create()(TeamBuying);

export default TeamBuyings


